package com.siteseat.crudeq.client.v1.request;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Collection;
import java.util.List;

import com.siteseat.common.misc.IOHelper;
import com.siteseat.crudeq.client.ClientMessage;
import com.siteseat.crudeq.client.ClientProfile;
import com.siteseat.crudeq.client.CommandConnection;
import com.siteseat.crudeq.client.PublishResult;
import com.siteseat.crudeq.client.QueueHistory;
import com.siteseat.crudeq.common.raw.protocol.v1.V1RequestId;
import com.siteseat.crudeq.common.raw.protocol.v1.V1ResponseId;

public class V1CommandConnection extends V1Connection implements CommandConnection {


  /**
   *
   *
   */
  public V1CommandConnection() {
    super();
  }

  /**
   *
   *
   * @param profile
   * @throws IOException
   */
  public V1CommandConnection( ClientProfile profile ) throws IOException {
    super( profile );
  }

  /**
   * {@inheritDoc}
   */
  @SuppressWarnings( "unchecked" )
  @Override
  public List<ClientMessage> history( Collection<QueueHistory> messageIds ) throws IOException {
    ensureLogined();

    OutputStream upStream = getUpStream();
    
    upStream.write( V1RequestId.HISTORY );

    int count = messageIds.size();

    IOHelper.writeInt( upStream, 4 + count * ( 8 + 4 + 4 ) );
    IOHelper.writeInt( upStream, count );

    for( QueueHistory mid: messageIds ) {

      long chunkId = mid.getChunkId();
      int offset = mid.getOffset();
      int queueId = mid.getQueueId().intValue();

      IOHelper.writeLong( upStream, chunkId );
      IOHelper.writeInt( upStream, offset );
      IOHelper.writeInt( upStream, queueId );
    }

    return (List<ClientMessage>)handleResponse( V1ResponseId.MESSAGE_SET, V1ResponseId.NO_MESSAGE );
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public PublishResult click( int queueId, byte[] payload ) throws IOException {
    ensureLogined();

    OutputStream upStream = getUpStream();
    
    upStream.write( V1RequestId.CLICK );

    IOHelper.writeInt( upStream, 4 + 4 + payload.length );

    IOHelper.writeInt( upStream, queueId );
    IOHelper.writeInt( upStream, payload.length );
    upStream.write( payload );

    return (PublishResult)handleResponse( V1ResponseId.PUBLISHED );
  }
  

  /**
   * {@inheritDoc}
   */
  @Override
  public PublishResult click( int queueId, String payload ) throws IOException {
    ensureLogined();

    byte[] p = payload.getBytes( IOHelper.CHARSET );
    
    OutputStream upStream = getUpStream();
    
    upStream.write( V1RequestId.CLICK );

    IOHelper.writeInt( upStream, 4 + 4 + p.length );

    IOHelper.writeInt( upStream, queueId );
    IOHelper.writeInt( upStream, p.length );
    upStream.write( p );

    return (PublishResult)handleResponse( V1ResponseId.PUBLISHED );
  }

  
}
